package com.wn.search.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.wn.common.model.dto.borrow.BorrowQuery;
import com.wn.common.model.vo.borrow.BorrowRecordVo;
import com.wn.common.utils.Pages;
import com.wn.search.entity.BorrowVO;
import com.wn.search.service.IBorrowRecordService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yellow Docter
 * @date 2023 -03-06
 * @desc
 */
@Service
@Slf4j
public class BorrowRecordServiceImpl implements IBorrowRecordService {

    //搜索模板
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public Pages<BorrowVO> borrowSearch(BorrowQuery borrowQuery, Integer currentPage, Integer pageSize) {

        //1、条件判断
        //2、构建 query （搜索条件查询）
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //条件判断
        if (borrowQuery.getBorrowStatus() != null) {
            queryBuilder.withQuery(QueryBuilders.matchQuery("borrowStatus",borrowQuery.getBorrowStatus()));
        }
        if (StringUtils.isNotEmpty(borrowQuery.getName() )) {
            queryBuilder.withQuery(QueryBuilders.matchQuery("name",borrowQuery.getName()));
        }

        if (borrowQuery.getStartPeriod() != null ){
            queryBuilder.withQuery(QueryBuilders.rangeQuery("period").gte(borrowQuery.getStartPeriod()));
        }

        if (borrowQuery.getEndPeriod() != null ){
            queryBuilder.withQuery(QueryBuilders.rangeQuery("period").lte(borrowQuery.getEndPeriod()));
        }

        //构建搜索条件
        NativeSearchQuery searchQuery = queryBuilder.build();

        //进行分页
        //从 0 开始
        searchQuery.setPageable(PageRequest.of(currentPage-1,pageSize));

        //调用方法
        SearchHits<BorrowVO> searchHits = elasticsearchRestTemplate.search(searchQuery, BorrowVO.class);

        long totalHits = searchHits.getTotalHits();
        log.info("搜索的数据是:{}",searchHits);

        List<BorrowVO> borrowVOS = searchHits.stream().map(searchHit -> searchHit.getContent()).collect(Collectors.toList());
        //3、返回结果 封装 一个  Pages

        Pages<BorrowVO> pages = new Pages<>();
        pages.setPageNum(currentPage);
        pages.setPageSize(pageSize);
        pages.setTotal(totalHits);
        pages.setList(borrowVOS);

        return pages;
    }


}
